import React from 'react';
import axios from 'axios';
import {useMutation,useQuery,useQueryClient} from 'umi';



import styles from './products.less';
import ProductList from '@/components/ProductList';

export default function Page() {
  const queryClient = useQueryClient();
  const productsQuery = useQuery(['products'],{
    queryFn:async ()=>{
      const {data} = await axios.get('/api/products');
      return data;
    }
  });
  const productsDeleteMutation  = useMutation({
    mutationFn:async (id:string)=>{
      await axios.delete(`/api/products/${id}`);
    },
    onSuccess:()=>{
      queryClient.invalidateQueries({queryKey:['products']});
    }
  });
  if(productsQuery.isLoading){
    return null;
  }

  return (
    <div>
      <h1 className={styles.title}>Page products</h1>
      <ProductList
        products={productsQuery.data.data}
        onDelete={(id:string)=>{
          productsDeleteMutation.mutate(id);
        }}
      />
    </div>
  );
}
